﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using FTBS.Models.BLO;
using FTBS.Models.Entities;
using PagedList;

namespace FTBS.Controllers
{
    public class PromotionController : Controller
    {
        PromotionBLO _promotionBo = new PromotionBLO();

        /// <summary>
        /// show list promotions
        /// </summary>
        /// <returns></returns>
        /// <author>hungph</author>
        /// <date>3/7/2014</date>
        public ActionResult Index(string sortOrder, string currentFilter, string searchString, int? page, bool? isSortDescending)
        {
            if (this.Session["RoleName"] == null || this.Session["UserName"] == null || this.Session["Account"] == null || this.Session["RoleName"].ToString().Trim() != "Staff")
            {
                return Redirect("/Home/Announcement");
            }

            List<Promotion> listPromotion = new List<Promotion>();
            listPromotion = _promotionBo.LoadPromotionsOrderById();

            ViewBag.NameSortParm = "name_desc";
            ViewBag.CurrentSort = sortOrder;

            if (searchString != null)
            {
                page = 1;
            }
            else
            {
                searchString = currentFilter;
            }

            ViewBag.CurrentFilter = searchString;
            ViewBag.IsSortDes = false;

            if (!String.IsNullOrEmpty(searchString))
            {
                listPromotion = listPromotion.Where(promotion => promotion.PromotionName.ToUpper().Contains(searchString.ToUpper())
                                                  || promotion.FromDate.ToString().Contains(searchString.ToUpper())
                                                  || promotion.ToDate.ToString().Contains(searchString.ToUpper())
                                                  || promotion.Rate.ToString().ToUpper().Contains(searchString.ToUpper())).ToList();
            }

            switch (sortOrder)
            {
                case "name_desc":
                    if (isSortDescending == true)
                    {
                        listPromotion = listPromotion.OrderByDescending(promotion => promotion.PromotionName).ToList();
                        ViewBag.IsSortDes = false;
                    }
                    else
                    {
                        listPromotion = listPromotion.OrderBy(promotion => promotion.PromotionName).ToList();
                        ViewBag.IsSortDes = true;
                    }
                    break;
                case "fromDate_desc":
                    if (isSortDescending == true)
                    {
                        listPromotion = listPromotion.OrderByDescending(promotion => promotion.FromDate).ToList();
                        ViewBag.IsSortDes = false;
                    }
                    else
                    {
                        listPromotion = listPromotion.OrderBy(promotion => promotion.FromDate).ToList();
                        ViewBag.IsSortDes = true;
                    }
                    break;
                case "toDate_desc":
                    if (isSortDescending == true)
                    {
                        listPromotion = listPromotion.OrderByDescending(promotion => promotion.ToDate).ToList();
                        ViewBag.IsSortDes = false;
                    }
                    else
                    {
                        listPromotion = listPromotion.OrderBy(promotion => promotion.ToDate).ToList();
                        ViewBag.IsSortDes = true;
                    }
                    break;
                case "rate_desc":
                    if (isSortDescending == true)
                    {
                        listPromotion = listPromotion.OrderByDescending(promotion => promotion.Rate).ToList();
                        ViewBag.IsSortDes = false;
                    }
                    else
                    {
                        listPromotion = listPromotion.OrderBy(promotion => promotion.Rate).ToList();
                        ViewBag.IsSortDes = true;
                    }
                    break;
                default:
                    listPromotion = listPromotion.OrderBy(promotion => promotion.PromotionId).ToList();
                    ViewBag.IsSortDes = false;
                    break;
            }

            int pageSize = 5;
            int pageNumber = (page ?? 1);

            return View(listPromotion.ToPagedList(pageNumber, pageSize));
        }

        /// <summary>
        /// render create page
        /// </summary>
        /// <returns></returns>
        /// <author>hungph</author>
        /// <date>3/7/2014</date>
        public ActionResult Create()
        {
            if (this.Session["RoleName"] == null || this.Session["UserName"] == null || this.Session["Account"] == null || this.Session["RoleName"].ToString().Trim() != "Staff")
            {
                return Redirect("/Home/Announcement");
            }
            ViewBag.PromotionName = null;
            ViewBag.FromDateValue = DateTime.Today;
            ViewBag.ToDateValue = DateTime.Today;
            ViewBag.IsValidateDate = 0;
            return View();
        }

        /// <summary>
        /// Create a promotion
        /// </summary>
        /// <param name="promotion"></param>
        /// <returns></returns>
        /// <author>hungph</author>
        /// <edit>VuongVT</edit>
        /// <date>3/7/2014</date>
        [HttpPost]
        public ActionResult Create(Promotion promotion, HttpPostedFileBase fileImage, string toDateValue, string fromDateValue)
        {
            if (this.Session["RoleName"] == null || this.Session["UserName"] == null || this.Session["Account"] == null || this.Session["RoleName"].ToString().Trim() != "Staff")
            {
                return Redirect("/Home/Announcement");
            }
            int validateResult = 0;

            //Convert string fromDateValue to DateTime
            var arrayFromDate = fromDateValue.Split('/');
            var fromDay = Convert.ToInt32(arrayFromDate[0]);
            var fromMonth = Convert.ToInt32(arrayFromDate[1]);
            var fromYear = Convert.ToInt32(arrayFromDate[2]);
            DateTime fromDate = new DateTime(fromYear, fromMonth, fromDay);

            //Convert string toDateValue to DateTime
            var arrayToDate = toDateValue.Split('/');
            var toDay = Convert.ToInt32(arrayToDate[0]);
            var toMonth = Convert.ToInt32(arrayToDate[1]);
            var toYear = Convert.ToInt32(arrayToDate[2]);
            DateTime toDate = new DateTime(toYear, toMonth, toDay);

           

            //Check user choosen FromDate and ToDate or not
            if (fromDate == DateTime.MinValue)
            {
                validateResult = 4; //Not select FromDate
                ViewBag.PromotionName = null;
                ViewBag.FromDateValue = DateTime.Today;
                ViewBag.ToDateValue = DateTime.Today;
                ViewBag.IsValidateDate = validateResult;
                return View(promotion);
            }
            else if (toDate == DateTime.MinValue)
            {
                validateResult = 5; //Not select ToDate
                ViewBag.PromotionName = null;
                ViewBag.FromDateValue = DateTime.Today;
                ViewBag.ToDateValue = DateTime.Today;
                ViewBag.IsValidateDate = validateResult;
                return View(promotion);
            }

            //If choose fromDate and toDate => compare
            validateResult = _promotionBo.IsValidateFromAndToDate(fromDate, toDate);

            if (validateResult == 0)
            {
                promotion.FromDate = fromDate;
                promotion.ToDate = toDate;
                if (fileImage != null)
                {
                    ModelState.Remove("ImageURL");
                    promotion.ImageURL = fileImage.FileName;
                }
                else
                {
                    ViewBag.PromotionName = null;
                    ViewBag.FromDateValue = promotion.FromDate;
                    ViewBag.ToDateValue = promotion.ToDate;
                    ViewBag.IsValidateDate = validateResult;
                    return View(promotion);
                }

                if (ModelState.IsValid)
                {
                    try
                    {
                        if (!_promotionBo.CheckIsExistedCreate(promotion))
                        {
                            if (fileImage != null)
                            {
                                fileImage.SaveAs(HttpContext.Server.MapPath("~/Image/Promotion/") + fileImage.FileName);
                                promotion.ImageURL = fileImage.FileName;

                                ViewBag.PromotionName = null;
                                ViewBag.IsValidateDate = validateResult;
                                ViewBag.FromDateValue = promotion.FromDate;
                                ViewBag.ToDateValue = promotion.ToDate;
                                _promotionBo.CreatePromotion(promotion);
                                return RedirectToAction("Index");
                            }
                            else
                            {
                                ViewBag.PromotionName = null;
                                ViewBag.FromDateValue = promotion.FromDate;
                                ViewBag.ToDateValue = promotion.ToDate;
                                ViewBag.IsValidateDate = validateResult;
                                _promotionBo.CreatePromotion(promotion);
                                return RedirectToAction("Index");
                            }
                        }
                        else
                        {
                            ViewBag.PromotionName = promotion.PromotionName;
                            ViewBag.FromDateValue = promotion.FromDate;
                            ViewBag.ToDateValue = promotion.ToDate;
                            ViewBag.IsValidateDate = validateResult;
                            return View(promotion);
                        }
                    }
                    catch (Exception)
                    {
                        ViewBag.PromotionName = null;
                        ViewBag.FromDateValue = promotion.FromDate;
                        ViewBag.ToDateValue = promotion.ToDate;
                        ViewBag.IsValidateDate = validateResult;
                        return View(promotion);
                    }
                }
                else
                {
                    ViewBag.PromotionName = null;
                    ViewBag.FromDateValue = promotion.FromDate;
                    ViewBag.ToDateValue = promotion.ToDate;
                    ViewBag.IsValidateDate = validateResult;
                    return View(promotion);
                }
            }
            
            ViewBag.PromotionName = null;
            ViewBag.FromDateValue = promotion.FromDate;
            ViewBag.ToDateValue = promotion.ToDate;
            ViewBag.IsValidateDate = validateResult;
            return View(promotion);
        }

        /// <summary>
        /// render Edit page
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        /// <author>hungph</author>
        /// <edit>VuongVT</edit>
        /// <date>3/7/2014</date>
        public ActionResult Edit(int id)
        {
            if (this.Session["RoleName"] == null || this.Session["UserName"] == null || this.Session["Account"] == null || this.Session["RoleName"].ToString().Trim() != "Staff")
            {
                return Redirect("/Home/Announcement");
            }
            if (_promotionBo.IsPromotionUsedForScheduleAndBooked(id))
            {
                TempData["IsUsedInSchedule"] = true;
                return RedirectToAction("Index");
            }
            else
            {
                ViewBag.PromotionName = null;
                Promotion promotion = _promotionBo.LoadPromotionById(id);
                ViewBag.FromDateValue = promotion.FromDate;
                ViewBag.ToDateValue = promotion.ToDate;
                ViewBag.IsValidateDate = 0;
                if (promotion == null)
                {
                    return HttpNotFound();
                }
                return View(promotion);
            }
        }

        /// <summary>
        /// edit info of Editing promotion
        /// </summary>
        /// <param name="promotion"></param>
        /// <returns></returns>
        /// <author>hungph</author>
        /// <edit>VuongVT</edit>
        /// <date>3/7/2014</date>
        [HttpPost]
        public ActionResult Edit(Promotion promotion, HttpPostedFileBase fileImageUpdate, string toDateValue, string fromDateValue)
        {
            if (this.Session["RoleName"] == null || this.Session["UserName"] == null || this.Session["Account"] == null || this.Session["RoleName"].ToString().Trim() != "Staff")
            {
                return Redirect("/Home/Announcement");
            }
            var id = promotion.PromotionId;
            int validateResult = 0;

            //Convert string fromDateValue to DateTime
            var arrayFromDate = fromDateValue.Split('/');
            var fromDay = Convert.ToInt32(arrayFromDate[0]);
            var fromMonth = Convert.ToInt32(arrayFromDate[1]);
            var fromYear = Convert.ToInt32(arrayFromDate[2]);
            DateTime fromDate = new DateTime(fromYear, fromMonth, fromDay);

            //Convert string toDateValue to DateTime
            var arrayToDate = toDateValue.Split('/');
            var toDay = Convert.ToInt32(arrayToDate[0]);
            var toMonth = Convert.ToInt32(arrayToDate[1]);
            var toYear = Convert.ToInt32(arrayToDate[2]);
            DateTime toDate = new DateTime(toYear, toMonth, toDay);

            //Check user choosen FromDate and ToDate or not
            if (fromDate == DateTime.MinValue)
            {
                validateResult = 4; //Not select FromDate
                ViewBag.PromotionName = null;
                ViewBag.FromDateValue = DateTime.Today;
                ViewBag.ToDateValue = DateTime.Today;
                ViewBag.IsValidateDate = validateResult;
                return View(promotion);
            }
            else if (toDate == DateTime.MinValue)
            {
                validateResult = 5; //Not select ToDate
                ViewBag.PromotionName = null;
                ViewBag.FromDateValue = DateTime.Today;
                ViewBag.ToDateValue = DateTime.Today;
                ViewBag.IsValidateDate = validateResult;
                return View(promotion);
            }

            validateResult = _promotionBo.IsValidateFromAndToDate(fromDate, toDate);
            promotion.FromDate = fromDate;
            promotion.ToDate = toDate;
            if (validateResult == 0)
            {
                
                if (ModelState.IsValid)
                {
                    if (!_promotionBo.CheckIsExistedEdit(promotion))
                    {
                        if (fileImageUpdate != null)
                        {
                            if (fileImageUpdate.FileName.Equals(promotion.ImageURL))
                            {
                                fileImageUpdate.SaveAs(HttpContext.Server.MapPath("~/Image/Promotion/") + fileImageUpdate.FileName);
                                promotion.ImageURL = fileImageUpdate.FileName;
                            }
                            else if (!fileImageUpdate.FileName.Equals(promotion.ImageURL))
                            {
                                if (promotion.ImageURL != null)
                                {
                                    System.IO.File.Delete(HttpContext.Server.MapPath("~/Image/Promotion/") + promotion.ImageURL);
                                }
                                fileImageUpdate.SaveAs(HttpContext.Server.MapPath("~/Image/Promotion/") + fileImageUpdate.FileName);
                                promotion.ImageURL = fileImageUpdate.FileName;
                            }
                        }
                        ViewBag.PromotionName = null;
                        ViewBag.FromDateValue = promotion.FromDate;
                        ViewBag.ToDateValue = promotion.ToDate;
                        ViewBag.IsValidateDate = validateResult;
                        _promotionBo.EditPromotion(promotion);
                        return RedirectToAction("Index");
                    }
                    else
                    {
                        ViewBag.PromotionName = promotion.PromotionName;
                        ViewBag.FromDateValue = promotion.FromDate;
                        ViewBag.ToDateValue = promotion.ToDate;
                        ViewBag.IsValidateDate = validateResult;
                        return View(promotion);
                    }
                }
                else
                {
                    ViewBag.PromotionName = null;
                    ViewBag.FromDateValue = promotion.FromDate;
                    ViewBag.ToDateValue = promotion.ToDate;
                    ViewBag.IsValidateDate = validateResult;
                    return View(promotion);
                }
            }

            ViewBag.PromotionName = null;
            ViewBag.FromDateValue = promotion.FromDate;
            ViewBag.ToDateValue = promotion.ToDate;
            ViewBag.IsValidateDate = validateResult;
            return View(promotion);
        }

        /// <summary>
        /// view details of promotion
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        /// <author>hungph</author>
        /// <date>3/7/2014</date>
        public ActionResult Details(int id)
        {
            if (this.Session["RoleName"] == null || this.Session["UserName"] == null || this.Session["Account"] == null || this.Session["RoleName"].ToString().Trim() != "Staff")
            {
                return Redirect("/Home/Announcement");
            }
            Promotion promotion = _promotionBo.LoadPromotionById(id);
            if (promotion == null)
            {
                return HttpNotFound();
            }
            ViewBag.Promotion = promotion;
            return View(promotion);
        }

        /// <summary>
        /// delete a promotion
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        /// <author>hungph</author>
        /// <date>3/7/2014</date>
        [HttpDelete, ActionName("Delete")]
        public ActionResult Delete(int id = 0)
        {
            if (this.Session["RoleName"] == null || this.Session["UserName"] == null || this.Session["Account"] == null || this.Session["RoleName"].ToString().Trim() != "Staff")
            {
                return Redirect("/Home/Announcement");
            }
            if (_promotionBo.IsPromotionUsedForSchedule(id))
            {
                TempData["CanNotDelete"] = true;
                return RedirectToAction("Index");
            }
            else
            {
                Promotion promotion = _promotionBo.LoadPromotionById(id);
                if (promotion == null)
                {
                    return HttpNotFound();
                }
                var isSuccess = _promotionBo.DeletePromotion(promotion);
                if (isSuccess)
                {
                    return RedirectToAction("Index");
                }
                return RedirectToAction("Index");
            }
        }

    }
}
